package com.chiang.apntest.activity;

import org.apache.cordova.DroidGap;

import com.chiang.apntest.common.Constant;
import com.chiang.apntest.service.SysMessageService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

public class MainActivity extends DroidGap{

	private static final int REFRESH_MESSAGE=0;
//	Handler mHandler=new Handler(){
//
//		@Override
//		public void handleMessage(Message msg) {
//			super.handleMessage(msg);
//			if(msg.what==REFRESH_MESSAGE){
//				sendBroadCast();
//			}
//		}
//		
//	};
	
	BroadcastReceiver receiver=new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action=intent.getAction();
			if(null!=action&& Constant.NEW_SYS_MESSAGE_ACTION.equals(action)){
				String message=intent.getStringExtra("message");
				if(null!=message)
					refreshMessage(message);
			}
		}
		
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(new View(this));
		super.loadUrl("file:///android_asset/www/index.html");
		
		IntentFilter filter=new IntentFilter();
		filter.addAction(Constant.NEW_SYS_MESSAGE_ACTION);
		
		registerReceiver(receiver, filter);
		//模拟接受到服务的新信息，发送广播请求更新页面
//		mHandler.sendEmptyMessageDelayed(REFRESH_MESSAGE, 4000);
//		this.sendJavascript("");
	}

	protected void sendBroadCast() {
		Intent intent=new Intent(Constant.NEW_SYS_MESSAGE_ACTION);
		intent.putExtra("message", "来自服务器端的消息");
		this.sendBroadcast(intent);
	}

	protected void refreshMessage(String message) {
		sendJavascript("refreshMessage('"+message+"')");
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(receiver);
		Intent intent=new Intent();
		intent.setClass(getApplicationContext(), SysMessageService.class);
		stopService(intent);
		super.onDestroy();
	}

	
}
